package com.foundersoftware.loader.initialization;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Loader initialization sysytem class.
 * @author	JiDong
 * @create	December 2.2009	
 *
 */
public class LoaderInitializationSystem implements ServletContextListener{
	
	private static final Log log = LogFactory.getLog(LoaderInitializationSystem.class);
	private static ServletContext servletContext;
	
	public void contextDestroyed(ServletContextEvent event) {
		log.info("***********Loader Initalization Start********************************");
		
		this.servletContext = event.getServletContext();

		LoaderInitializationSystem loader = new LoaderInitializationSystem();
		String path = servletContext.getRealPath("");	
		List<String> templateNames = loader.getTemplateName(path+"/template");
		servletContext.setAttribute("templateNames",templateNames);
		
		path = null;
		log.info("***********Loader Initalization End********************************");
	}

	public void contextInitialized(ServletContextEvent event) {
		contextDestroyed(event);
	}
	
	public  List<String> getTemplateName(String dir){
		List<String> templateNames = new ArrayList<String>();
		File files = new File(dir);		
		 /*is it directory ? */
		if(!files.isDirectory()){			
			String name = files.getName();			
			/*is it suffix .xls or .xlsx file */
			if(internalFilterEndWith(name)){			 
				templateNames.add(name);
			}
			
			name = null;	
		}else if (files.isDirectory()){
			String [] filelist = files.list();			
			findChildFile(dir, templateNames, filelist);
			filelist = null;
		}
		files = null;
		
		return templateNames;
	}

	private void findChildFile(String dir, List<String> templateNames,
			String[] filelist) {
		for(int i = 0; i < filelist.length; i++){
			File readFiles = new File(dir + "\\" + filelist[i]);			
			/*is it directory ?*/
			if(!readFiles.isDirectory()){
				String name = readFiles.getName();					
				/*it is suffix .java file ?*/
				if(internalFilterEndWith(name)){
					templateNames.add(name);
				}
				
				name = null;				
			}else if (readFiles.isDirectory()){
				/*recursive invoke reader file */
				getTemplateName(dir + "\\" + filelist[i]);
			}
			readFiles = null;
		}
	}
	

	/**
	 * Is it suffix .xls file ?
	 * @param name
	 * @return
	 */
	private boolean internalFilterEndWith(String name){
		if (name.endsWith(".xls") || name.endsWith(".xlsx")) {
			return true;
		}
		return false;
		
	}

}
